package risoe.syslab.fhnew.hw;

/*
 * Copyright (c) 2012-2014, Technical University of Denmark (DTU)
 * All rights reserved.
 * 
 * The Flexhouse 2.0 platform ("this software") is licensed under the
 * BSD 3-clause license.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   - Neither the name of DTU nor the names of its contributors may be used to
 *     endorse or promote products derived from this software without specific
 *     prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE TECHNICAL UNIVERSITY OF DENMARK BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import risoe.syslab.fhnew.db.PlatformEventLogger;

/**
 * Utility class capable of managing the connection of a HardwareInterface by handling timeouts and reconnection.
 * @author M. Svendsen
 */
public class ConnectionManager {
	private static final int RECONNECT_TIMEOUT = 10000;

	private boolean mUsesTimeouts = true;
	private boolean mShouldBeConnected = true;
	private boolean mIsConnected = false;
	private int mTimeoutMillis;
	private long mDisconnectTime;
	private int mReconnectAttempts;

	// Executor shared by all ConnectionManagers
	private static ScheduledExecutorService mExecutor = Executors.newSingleThreadScheduledExecutor();

	private ConnectionManagerInterface mInterface;
	private PlatformEventLogger mLogger;

	private Runnable mReconnectTask = new Runnable() {
		@Override
		public void run() {
			mReconnectAttempts++;
			mLogger.logEvent(mInterface.getName(), "Connection", "Attempting reconnect #"+mReconnectAttempts);
			
			// Attempt reconnect
			if (mInterface.connect()){
				// Success!
				long timeSinceDisconnect = System.currentTimeMillis() - mDisconnectTime;
				mLogger.logEvent(mInterface.getName(), "Connection", "Interface Reconnected after "+timeSinceDisconnect+
						"ms and "+mReconnectAttempts+" attempts");
				mIsConnected = true;
				if (mUsesTimeouts){
					signal();
				}
			}
			else{
				mExecutor.schedule(this, RECONNECT_TIMEOUT, TimeUnit.MILLISECONDS);
			}
		}
	};

	private Future<?> mTimeoutFuture = null;
	private Runnable mConnectionTimeout = new Runnable() {

		@Override
		public void run() {
			// If this runs, the interface has received no new data for a period longer than specified
			// Attempt to check if interface is still connected
			if (mInterface.probeConnection()){
				// Probe was successful. Connection is still valid
				signal();
			}
			else{
				// Connection could not be verified. Assume to be down and try reconnecting
				onDisconnected();
			}
		}
	};

	/**
	 * Constructs a new ConnectionManager. Calling ConnectionManager.startConnection() will 
	 * initiate the actual communication with hardware. The calling class must implement ConnectionManagerInterface.
	 * This constructor sets a communication timeout of 0 seconds (no timeout).
	 * @param intf the HardwareInterface to which this ConnectionManager should be bound.
	 */
	public ConnectionManager(ConnectionManagerInterface intf){
		this(intf, 0);
	}

	/**
	 * Constructs a new ConnectionManager. Calling ConnectionManager.startConnection() will 
	 * initiate the actual communication with hardware. The calling class must implement ConnectionManagerInterface.
	 * @param intf the HardwareInterface to which this ConnectionManager should be bound.
	 * @param timeoutMillis a timeout in milliseconds used to determine whether a communication channel might
	 * have broken down. A timeout of 0 seconds indicate no timeout.
	 */
	public ConnectionManager(ConnectionManagerInterface intf, int timeoutMillis) {
		mInterface = intf;
		mLogger = intf.getLogger();

		// Check if this interface wishes to handle disconnects by itself ...
		if (timeoutMillis == 0){
			mUsesTimeouts = false;
		}
		// or use the signal/timeout feature
		else{
			mTimeoutMillis = timeoutMillis;
		}

	}

	/**
	 * Signals to the ConnectionManager that data has been successfully sent or received from hardware. 
	 * This function should be called from any send/receive methods to reset the timeout of the ConnectionManager.
	 * Note, if the set timeout is equal to 0, this function can be ignored.
	 */
	public void signal() {
		if (!mUsesTimeouts) return;

		if (mTimeoutFuture != null){
			mTimeoutFuture.cancel(true);
		}

		if (!mExecutor.isShutdown()){
			mTimeoutFuture = mExecutor.schedule(mConnectionTimeout, mTimeoutMillis, TimeUnit.MILLISECONDS);
		}
	}

	/**
	 * Called when a disconnection has been detected. Can also be called by the governing HardwareInterface
	 * is a disconnect is detected directly, i.e. by catching an IOException.
	 */
	public void onDisconnected() {
		mLogger.logEvent(mInterface.getName(), "Connection", "Interface Disconnected");
		mDisconnectTime = System.currentTimeMillis();

		if (mIsConnected){
			mIsConnected = false;
			mInterface.disconnect();
		}
		if (mTimeoutFuture != null){
			mTimeoutFuture.cancel(true);
			mTimeoutFuture = null;
		}

		if (mShouldBeConnected && !mExecutor.isShutdown()){
			mReconnectAttempts = 0;
			mExecutor.schedule(mReconnectTask, 0, TimeUnit.MILLISECONDS);
		}
	}

	/**
	 * Starts the connection and begins monitoring of timeout if applicable.
	 */
	public void startConnection() {
		mShouldBeConnected = true;
		if (mInterface.connect()){
			mIsConnected = true;
			mLogger.logEvent(mInterface.getName(), "Connection", "Interface Connected");
			signal();
		}
		else{
			onDisconnected();
		}
	}

	/**
	 * Stops the connection and ends all monitoring of timeouts / reconnection.
	 */
	public void stopConnection() {
		mShouldBeConnected = false;
		onDisconnected();
	}

	/**
	 * @return a boolean indicating the state of this connection.
	 */
	public boolean isConnected() {
		return mIsConnected;
	}
}
